package com.guestmanage.servlet.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class BaseAction {
	
	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;
	
	public BaseAction(HttpServletRequest request,HttpServletResponse response){
		this.request=request;
		this.response=response;
		this.session=request.getSession();
	}
	
	public void setSessionAttribute(String arg0,Object obj){
		session.setAttribute(arg0, obj);
	}
	
	public Object getSessionAttribute(String arg0){
		return session.getAttribute(arg0);
	}
	
	public String getParameterString(String args){
		return request.getParameter(args);
	}
	
	public int getParameterInt(String args){
		try {
			return Integer.parseInt(request.getParameter(args));
		} catch (Exception e) {
			return 0;
		}
	}
	
	public long getParameterLong(String args){
		try {
			return Long.parseLong(request.getParameter(args));
		} catch (NumberFormatException e) {
			return 0;
		}
	}
	
	public void setAttribute(String args,Object obj){
		request.setAttribute(args, obj);
	}
	
	public void printWriter(String args){
		response.setCharacterEncoding("UTF-8");
		PrintWriter out=null;
		try {
			out=response.getWriter();
			out.print(args);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			out.close();
		}
	}
	
	public void forward(String url){
		try {
			request.getRequestDispatcher(url).forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void sendRedirect(String url){
		try {
			response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String[] getParameterValuesString(String args){
		return request.getParameterValues(args);
	}
	
	public int[] getParameterValuesInt(String args){
		String[] str=request.getParameterValues(args);
		int[] intStr=new int[str.length];
		for(int i=0;i<str.length;i++){
			intStr[i]=Integer.parseInt(str[i]);
		}
		return intStr;
	}
}
